#include <func.h>

typedef struct
{
    int file_len;
    char file_name[50];
} File;

// 服务端
int main(void)
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);

    int reuse = 1;
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi("8080"));
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    bind(fd, (struct sockaddr*)&addr, sizeof(addr));
    listen(fd, 10);

    int sock_fd = accept(fd, NULL, NULL);

    printf("已连接用户\n");
    fd_set set;
    FD_ZERO(&set);
    FD_SET(sock_fd, &set);

    select(20, &set, NULL, NULL, NULL);

    if(FD_ISSET(sock_fd, &set))
    {
        File file;
        memset(&file, 0, sizeof(file));
        int count = recv(sock_fd, &file, sizeof(file), 0);
        printf("count = %d\n", count);

        printf("文件名： %s\n", file.file_name);
        printf("count = %d\n", count);

        int file_fd = open(file.file_name, O_RDWR | O_CREAT, 0666);
        if(file_fd == -1)
            error(1, errno, "open");
        sleep(3);

        while(1)
        {
            char buf[128] = {0};
            int count = recv(sock_fd, buf, sizeof(buf), 0);
            if(count == 0)
            {
                printf("传输完成\n");
                break;
            }

            write(file_fd, buf, count);
        }
    }

    system("sha1sum a.mp4");
    close(sock_fd);
    close(fd);
    close(sock_fd);
    return 0;
}

